angular.module('nonghua.directives', [])

    .directive('insertSelect', function ($ionicLoading, $timeout, $rootScope, $state) {
        return {
            restrict: 'EA',
            replace: true,
            transclude: true,
            scope: {
                form: '=',
                option: '='
            },
            controller: function ($scope) {
                var path_to_brand = 'mobile_service_resources/select_data_info';
                $scope.change = function (data) {
                    console.log(data);
                };
                if(empty($scope.form)){
                    $scope.option.required=false;
                }else{
                    $scope.option.required=true;
                }
                $scope.option.optionSource = [{"id": "", "label": "请选择"}];
                _get_datasouce_result({
                    path: path_to_brand,
                    param: $scope.option.params,
                    resource: "select_data_info",
                    success: function (data) {
                        $scope.option.optionSource = [];
                        if (data.data) {
                            $scope.option.optionSource = data.data;

                            $scope.$apply();
                            if (!empty($scope.option.initValue)) {
                                $timeout(function () {
                                    $scope.option.value = $scope.option.initValue;
                                }, 500);
                            }

                        }
                    }
                });

            },
            templateUrl: 'templates/directive-templates/insertSelect.html'

        }
    })
    .directive('insertDate', function ($ionicLoading, $timeout, $rootScope, $state) {
        return {
            restrict: 'EA',
            replace: true,
            transclude: true,
            scope: {
                dateoption: '=',
                form:'=',
            },
            controller: function ($scope) {
                if (empty($scope.dateoption.level)) {
                    $scope.dateoption.level = 3;
                }
               
                if(empty($scope.form)){
                    $scope.dateoption.required=false;
                }else{
                    $scope.dateoption.required=true;
                }
                $scope.date = {};
                var currentDate = new Date();
                var currentYear = currentDate.getFullYear();
                var currentMonth = currentDate.getMonth() + 1;
                var currentDay = currentDate.getDate();
                if(empty($scope.dateoption.initYear)){
                    $scope.dateoption.initYear = currentYear.toString();
                }
                if(empty($scope.dateoption.initMonth)){
                    if(currentMonth<10){
                        $scope.dateoption.initMonth = '0'+currentMonth;
                    }else{
                        $scope.dateoption.initMonth = currentMonth.toString();
                    }
                }
                if(empty($scope.dateoption.initDay)){
                    if(currentDay<10){
                        $scope.dateoption.initDay = '0'+currentDay;
                    }else{
                        $scope.dateoption.initDay = currentDay.toString();
                    }
                }

                $scope.years = [{'id':'','label':"请选年"}];
                $scope.months = [{'id':'','label':"请选月"}];
                $scope.days = [{'id':'','label':"请选日"}];
                for(var i = 0;i <=7 ; i++){
                    $scope.years.push({'id':(currentYear +2 - i)+'','label':currentYear +2 - i});
                }

                for (var i = 1; i <= 12; i++) {
                    if (i < 10) {
                        $scope.months.push({'id': '0' + i, 'label': i});
                    } else {
                        $scope.months.push({'id': i + '', 'label': i});
                    }

                }
                for (var i = 1; i <= 31; i++) {
                    if (i < 10) {
                        $scope.days.push({'id': '0' + i, 'label': i});
                    } else {
                        $scope.days.push({'id': i + '', 'label': i});
                    }

                }
                if (!empty($scope.dateoption.initYear)) {
                    $timeout(function () {
                        $scope.dateoption.year = $scope.dateoption.initYear;
                        var initMonth = parseInt($scope.dateoption.initMonth);
                        if(initMonth<10){
                            initMonth = '0'+initMonth;
                        }else{
                            initMonth = initMonth+"";
                        }
                        $scope.dateoption.month = initMonth;
                        $scope.dateoption.day = $scope.dateoption.initDay;
                    }, 1000);
                }
            },
            templateUrl: 'templates/directive-templates/insertDate.html',

        }
    })
    .directive('insertAddress', function ($ionicLoading, $ionicPopover, $rootScope, $state, $timeout) {
        return {
            restrict: 'EA',
            replace: true,
            transclude: true,
            scope: {
                addressoption: '=',
                form:'='
            },
            controller: function ($scope) {
                $scope.provinceSource = [
                    {'id': "", 'label': '请选省'},
                    {'id': "2", "label": "北京市"},
                    {'id': "19", "label": "天津市"},
                    {'id': "36", "label": "河北省"},
                    {'id': "230", "label": "山西省"},
                    {'id': "372", "label": "内蒙古自治区"},
                    {'id': "496", "label": "辽宁省"},
                    {'id': "625", "label": "吉林省"},
                    {'id': "703", "label": "黑龙江省"},
                    {'id': "857", "label": "上海市"},
                    {'id': "875", "label": "江苏省"},
                    {'id': "1001", "label": "浙江省"},
                    {'id': "1114", "label": "安徽省"},
                    {'id': "1252", "label": "福建省"},
                    {'id': "1356", "label": "江西省"},
                    {'id': "1479", "label": "山东省"},
                    {'id': "1651", "label": "河南省"},
                    {'id': "1845", "label": "湖北省"},
                    {'id': "1975", "label": "湖南省"},
                    {'id': "2125", "label": "广东省"},
                    {'id': "2285", "label": "广西壮族自治区"},
                    {'id': "2425", "label": "海南省"},
                    {'id': "2459", "label": "重庆市"},
                    {'id': "2498", "label": "四川省"},
                    {'id': "2721", "label": "贵州省"},
                    {'id': "2824", "label": "云南省"},
                    {'id': "2978", "label": "西藏自治区"},
                    {'id': "3063", "label": "陕西省"},
                    {'id': "3191", "label": "甘肃省"},
                    {'id': "3304", "label": "青海省"},
                    {'id': "3358", "label": "宁夏回族自治区"},
                    {'id': "3391", "label": "新疆维吾尔自治区"},
                    {'id': "3512", "label": " 台湾省"},
                    {'id': "3891", "label": "香港特别行政区"},
                    {'id': "3913", "label": "澳门特别行政区"},
                ]
                $scope.citySource = [{'id': "", "label": "请选市"}];
                $scope.countySource = [{'id': "", "label": "请选县"}];
                $scope.townSource = [{'id': "", "label": "请选乡镇"}];
                $scope.villageSource = [{'id': "", "label": "请选村落"}];
                $scope.farmerSource = [{'id': "", "label": "请选农户"}];
                if (empty($scope.addressoption.level)) {
                    $scope.addressoption.level = 5;
                }
                if(empty($scope.form)){
                    $scope.addressoption.required=false;
                }else{
                    $scope.addressoption.required=true;
                }
                if (!empty($scope.addressoption.init_farmer_id)) {
                    var path_to_view = 'mobile_service_resources/select_data_info';
                    var params = {
                        action: "get_addr_from_farmer",
                        init_farmer_id: $scope.addressoption.init_farmer_id,
                    };
                    _get_datasouce_result({
                        path: path_to_view,
                        param: params,
                        resource: "select_data_info",
                        success: function (data) {
                            if (data.data) {
                                $scope.addressoption.province = data.data.init_province;
                                if (data.city) {
                                    $scope.citySource = data.city;
                                }
                                if (data.county) {
                                    $scope.countySource = data.county;
                                }
                                if (data.town) {
                                    $scope.townSource = data.town;
                                }
                                if (data.village) {
                                    $scope.villageSource = data.village;
                                }
                                if (data.farmer) {
                                    $scope.farmerSource = data.farmer;
                                }
                                $scope.$apply();
                                $timeout(function () {
                                    $scope.addressoption.city = !empty(data.data.init_city) ? data.data.init_city : "";
                                    $scope.addressoption.county = !empty(data.data.init_county) ? data.data.init_county : "";
                                    $scope.addressoption.town = !empty(data.data.init_town) ? data.data.init_town : "";
                                    $scope.addressoption.village = !empty(data.data.init_village) ? data.data.init_village : "";
                                    $scope.addressoption.farmer = $scope.addressoption.init_farmer_id;
                                }, 1000)

                            }

                        }
                    });
                }
                if (!empty($scope.addressoption.init_addr_id)) {
                    var path_to_view = 'mobile_service_resources/select_data_info';
                    var params = {
                        action: "get_init_addr_id",
                        init_addr_id: $scope.addressoption.init_addr_id,
                    };
                    _get_datasouce_result({
                        path: path_to_view,
                        param: params,
                        resource: "select_data_info",
                        success: function (data) {
                            if (data.data) {
                                $scope.addressoption.province = data.data.init_province;
                                if (data.city) {
                                    $scope.citySource = data.city;
                                }
                                if (data.county) {
                                    $scope.countySource = data.county;
                                }
                                if (data.town) {
                                    $scope.townSource = data.town;
                                }
                                if (data.village) {
                                    $scope.villageSource = data.village;
                                }
                                $scope.$apply();
                                $timeout(function () {
                                    $scope.addressoption.city = !empty(data.data.init_city) ? data.data.init_city : "";
                                    $scope.addressoption.county = !empty(data.data.init_county) ? data.data.init_county : "";
                                    $scope.addressoption.town = !empty(data.data.init_town) ? data.data.init_town : "";
                                    $scope.addressoption.village = !empty(data.data.init_village) ? data.data.init_village : "";
                                    $scope.addressoption.farmer = !empty(data.data.init_farmer) ? data.data.init_farmer : "";
                                }, 1000)

                            }

                        }
                    });
                }

                $scope.getCity = function (province) {
                    $scope.citySource = [{'id': "", "label": "请选市"}];
                    $scope.countySource = [{'id': "", "label": "请选县"}];
                    $scope.townSource = [{'id': "", "label": "请选乡镇"}];
                    $scope.villageSource = [{'id': "", "label": "请选村落"}];
                    $scope.farmerSource = [{'id': "", "label": "请选农户"}];

                    $scope.addressoption.city = "";
                    $scope.addressoption.county = '';
                    $scope.addressoption.town = '';
                    $scope.addressoption.village = '';
                    $scope.addressoption.farmer = '';
                    var path_to_address = 'mobile_service_resources/select_data_info';
                    var params = {
                        action: "get_city",
                        province: province,
                    };
                    _get_datasouce_result({
                        path: path_to_address,
                        param: params,
                        resource: "select_data_info",
                        success: function (data) {
                            $scope.citySource = [];
                            $scope.countySource = [];
                            if (data.data) {
                                $scope.citySource = data.data;
                                if (!empty(data.extra)) {
                                    $scope.countySource = data.extra;
                                } else {
                                    $scope.countySource = [{'id': "", "label": "请选县"}];
                                }
                                if (params.province === "2") {
                                    var init_city = '3925';
                                } else if (params.province === "19") {
                                    var init_city = '3926';
                                } else if (params.province === "857") {
                                    var init_city = '3927';
                                } else if (params.province === "2459") {
                                    var init_city = '3928';
                                } else {
                                    var init_city = '';
                                }
                                $scope.addressoption.city = init_city;
                                $scope.addressoption.county = '';
                                $scope.addressoption.town = '';
                                $scope.addressoption.village = '';
                                $scope.addressoption.farmer = '';
                                $scope.$apply();
                            }
                        }
                    });
                };
                $scope.getCounty = function (city) {
                    $scope.countySource = [{'id': "", "label": "请选县"}];
                    $scope.townSource = [{'id': "", "label": "请选乡镇"}];
                    $scope.villageSource = [{'id': "", "label": "请选村落"}];
                    $scope.farmerSource = [{'id': "", "label": "请选农户"}];

                    $scope.addressoption.county = '';
                    $scope.addressoption.town = '';
                    $scope.addressoption.village = '';
                    $scope.addressoption.farmer = '';
                    var path_to_address = 'mobile_service_resources/select_data_info';
                    var params = {
                        action: "get_county",
                        city: city,
                    };
                    _get_datasouce_result({
                        path: path_to_address,
                        param: params,
                        resource: "select_data_info",
                        success: function (data) {
                            if (data.data) {
                                $scope.countySource = data.data;

                                $scope.addressoption.county = '';
                                $scope.addressoption.town = '';
                                $scope.addressoption.village = '';
                                $scope.$apply();
                            }
                        }
                    });
                };
                $scope.getTown = function (county) {

                    $scope.townSource = [{'id': "", "label": "请选乡镇"}];
                    $scope.villageSource = [{'id': "", "label": "请选村落"}];
                    $scope.farmerSource = [{'id': "", "label": "请选农户"}];

                    $scope.addressoption.town = '';
                    $scope.addressoption.village = '';
                    $scope.addressoption.farmer = '';

                    var path_to_address = 'mobile_service_resources/select_data_info';
                    var params = {
                        action: "get_town",
                        county: county,
                        farmer: $scope.addressoption.level >= 6 ? "get" : ""
                    };

                    _get_datasouce_result({
                        path: path_to_address,
                        param: params,
                        resource: "select_data_info",
                        success: function (data) {
                            if (data.data) {
                                $scope.townSource = data.data;
                                $scope.addressoption.town = '';
                                $scope.addressoption.village = '';
                                $scope.$apply();
                            }
                            if (data.farmer) {
                                $scope.farmerSource = data.farmer;
                                $scope.addressoption.farmer = '';
                                $scope.$apply();
                            }
                        }
                    });
                };
                $scope.getVillage = function (town) {
                    $scope.villageSource = [{'id': "", "label": "请选村落"}];
                    $scope.farmerSource = [{'id': "", "label": "请选农户"}];

                    $scope.addressoption.village = '';
                    $scope.addressoption.farmer = '';
                    var path_to_address = 'mobile_service_resources/select_data_info';
                    var params = {
                        action: "get_village",
                        town: town,
                        farmer: $scope.addressoption.level >= 6 ? "get" : ""
                    };
                    _get_datasouce_result({
                        path: path_to_address,
                        param: params,
                        resource: "select_data_info",
                        success: function (data) {
                            if (data.data) {
                                $scope.villageSource = data.data;
                                $scope.addressoption.village = '';
                                $scope.$apply();
                            }
                            if (data.farmer) {
                                $scope.farmerSource = data.farmer;

                                $scope.addressoption.farmer = '';
                                $scope.$apply();
                            }
                        }
                    });
                };

                $scope.getFarmer = function (addr) {
                    $scope.farmerSource = [{'id': "", "label": "请选农户"}];
                    $scope.addressoption.farmer = '';
                    var path_to_address = 'mobile_service_resources/select_data_info';
                    var params = {
                        action: "get_addr_farmer",
                        init_addr_id: addr,
                    };
                    _get_datasouce_result({
                        path: path_to_address,
                        param: params,
                        resource: "select_data_info",
                        success: function (data) {
                            if (data.data) {
                                $scope.farmerSource = data.data;

                                $scope.addressoption.farmer = '';
                                $scope.$apply();
                            }
                        }
                    });
                };
            },
            templateUrl: 'templates/directive-templates/insertAddress.html',

        }
    })
    .directive('ngTranscludeReplace', ['$log', function ($log) {
        return {
            terminal: true,
            restrict: 'EA',

            link: function ($scope, $element, $attr, ctrl, transclude) {
                if (!transclude) {
                    $log.error('orphan',
                        'Illegal use of ngTranscludeReplace directive in the template! ' +
                        'No parent directive that requires a transclusion found. ');
                    return;
                }
                transclude(function (clone) {
                    if (clone.length) {
                        $element.replaceWith(clone);
                    }
                    else {
                        $element.remove();
                    }
                });
            }
        };
    }])
    .directive('customComment', function ($ionicLoading, $ionicPopover, $rootScope, $state) {
        return {
            restrict: 'EA',
            replace: true,
            transclude: true,
            scope: {
                node: '=',
                comment: '=',
                text: '@'
            },
            controller: function ($scope) {

                $scope.data = {};
                $scope.submit_comment = function () {
                    if ($rootScope.user.uid == 0) {
                        $scope.closePopover();
                        alert("请登录后再进行操作");
                        $state.go('tabs.my-account');
                        return;
                    }
                    var comment = {
                        nid: $scope.node.nid,
                        subject: $scope.data.comment,
                        comment_body: {
                            und: [
                                {value: $scope.data.comment}
                            ]
                        }
                    };
                    $ionicLoading.show({
                        content: '请稍后',
                        animation: 'fade-in',
                        showBackdrop: true,
                        maxWidth: 200,
                        showDelay: 0
                    });
                    comment_save(comment, {
                        success: function (result) {
                            $ionicLoading.hide();
                            $scope.closePopover();

                            console.log(result);
                            var cid = result.cid;
                            $scope['comment'][cid] = {
                                cid: cid,
                                body: $scope.data.comment,
                                author: $rootScope.user.name,
                                author_pic: $rootScope.user.picture,
                                time: (new Date()).toLocaleTimeString()
                            };
                        }
                    });
                };
                $scope.popover = $ionicPopover.fromTemplateUrl('templates/directive-templates/comment-popover.html', {
                    scope: $scope
                });
                $ionicPopover.fromTemplateUrl('templates/directive-templates/comment-popover.html', {
                    scope: $scope
                }).then(function (popover) {
                    $scope.popover = popover;
                });
                $scope.openPopover = function ($event) {
                    if ($rootScope.user.uid == 0) {
                        alert("请登录后再进行操作");
                        $state.go('tabs.my-account');
                        return;
                    }
                    $scope.popover.show($event);
                };
                $scope.closePopover = function () {
                    $scope.popover.hide();
                };
            },
            templateUrl: 'templates/directive-templates/comment.html',

        }
    })
    .directive('followLike', function ($ionicLoading, $rootScope, $state) {
        return {
            restrict: 'EA',
            replace: true,
            transclude: true,
            scope: {
                node: '=',
                disabledlike: '=',
                disabledfollow: '=',
                disabledbutton: '=',
            },
            controller: function ($scope) {
                if ($scope.disabledbutton) {
                    $scope.button = "";
                } else {
                    $scope.button = "button";
                }
                var path_to_like = "expert/" + $scope.node.nid + "/like_follow";
                _rest_service_resources({
                    path: path_to_like,
                    method: 'GET',
                    success: function (data) {
                        $scope.node.likeNum = data.like_count;
                        $scope.node.followNum = data.follow_count;
                        data.self_follow == 1 ? $scope.node.follow = '已关注' : $scope.node.follow = '关注';
                        data.self_like == 1 ? $scope.node.like = '已赞' : $scope.node.like = '赞';
                        $scope.$apply();
                    }
                });

                $scope.NodeLikeAndFollow = function (nid, type) {
                    if ($rootScope.user.uid == 0) {
                        alert("请登录后再进行操作");
                        $state.go('tabs.my-account');
                        return;
                    }
                    $ionicLoading.show({
                        content: '请稍后',
                        animation: 'fade-in',
                        showBackdrop: true,
                        maxWidth: 200,
                        showDelay: 0
                    });
                    _rest_service_resources({
                        path: "expert/" + nid + "/like_follow",
                        method: 'POST',
                        param: {operate_name: type},
                        success: function (data) {

                            if (type == 'like') {
                                if (data.msg == 1) {
                                    $scope.node.like_counter = parseInt($scope.node.like_counter) + 1;
                                    $scope.node.like = '已赞';
                                } else {
                                    $scope.node.like_counter = parseInt($scope.node.like_counter) - 1;
                                    $scope.node.like = '赞';
                                }
                            } else if (type == 'follow') {
                                if (data.msg == 1) {
                                    $scope.node.follow_counter = parseInt($scope.node.follow_counter) + 1;
                                    $scope.node.follow = '已关注';
                                } else {
                                    $scope.node.follow_counter = parseInt($scope.node.follow_counter) - 1;
                                    $scope.node.follow = '关注';
                                }
                            }
                            $ionicLoading.hide();
                            $scope.$apply();
                        }
                    })
                };

            },
            templateUrl: 'templates/directive-templates/follow-like.html',

        }
    })
    .directive('confirmPass', function ($timeout) {
        return {
            restrict: 'EA',
            transclude: true,
            scope: {
                form: '=',
                password: '='
            },
            templateUrl: 'templates/directive-templates/confirmPass.html',
        }
    })
    .directive('checkDigit', function ($timeout) {
        return {
            restrict: 'EA',
            transclude: true,
            scope: {
                form: '=',
                data: '='
            },
            controller: function ($scope) {
                if (empty($scope.data.userCellDisabled)) {
                    $scope.data.userCellDisabled = false
                }
                $scope.checkButton = false;
                $scope.timeOut = 60;
                $scope.countDowner = function () {
                    if ($scope.timeOut <= 0) {
                        $scope.timeOut = 60;
                        $scope.buttonText = "重新获取校验码";
                        $scope.checkButton = false;
                        return; // quit
                    } else {
                        $scope.buttonText = $scope.timeOut + '秒'; // update scope
                        $scope.timeOut--;
                        $timeout($scope.countDowner, 1000); // loop it again
                    }
                }
                $scope.buttonText = "获取校验码";
                $scope.getDigit = function () {
                    $timeout(function () {
                        $scope.checkButton = true;
                    }, 100);

                    var url = 'sms&parameters[sms_cell]=' + $scope.data.userCell + '&parameters[graph_code]=' + $scope.data.graphCode;
                    _rest_service_resources({
                        path: url,
                        method: 'GET',
                        success: function (data) {
                            if (data.success == 0) {
                                $scope.countDowner();
                            } else {
                                alert(data.errorNum);
                                $scope.checkButton = false;
                            }
                            document.getElementById("graph_char").setAttribute("src", Drupal.settings.site_path + '/refreshGraph?' + Math.random());
                        }
                    });
                };

                document.getElementById("graph_char").setAttribute("src", Drupal.settings.site_path + '/refreshGraph?' + Math.random());
                $scope.refreshGraph = function() {
                    document.getElementById("graph_char").setAttribute("src", Drupal.settings.site_path + '/refreshGraph?' + Math.random());
                };

            },
            templateUrl: 'templates/directive-templates/checkDigit.html',

        }
    })

    .directive('confirmPwd', function ($interpolate, $parse) {
        return {
            require: 'ngModel',
            link: function (scope, elem, attr, ngModelCtrl) {

                var pwdToMatch = $parse(attr.confirmPwd);
                var pwdFn = $interpolate(attr.confirmPwd)(scope);

                scope.$watch(pwdFn, function (newVal) {
                    ngModelCtrl.$setValidity('password', ngModelCtrl.$viewValue == newVal);
                });

                ngModelCtrl.$validators.password = function (modelValue, viewValue) {
                    var value = modelValue || viewValue;
                    return value == pwdToMatch(scope);
                };

            }
        }
    });
